/**
 *
 */
package com.rf.richfitwheel.admin.sys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.shiro.PasswordExpired;
import com.rf.richfitwheel.admin.sys.dao.OrgMapper;
import com.rf.richfitwheel.admin.sys.dao.UserMapper;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.CodeUseInfoService;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.admin.sys.service.OrgService;
import com.rf.richfitwheel.admin.sys.service.SysUserMngOrgService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONObject;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hushouquan
 *
 */
@Service("orgService")
@RequiredArgsConstructor
public class OrgServiceImpl implements OrgService {
    
    @Autowired
    private OrgMapper orgMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ConfigService configService;
    @Autowired
    private SysUserMngOrgService sysUserMngOrgService;
    
//    private final FundAccountingFeign fundAccountingFeign;

    @Autowired
    private CodeUseInfoService codeUseInfoService;
    @Autowired
    private PasswordExpired passwordExpired;
    @Override
    public OrgVO getOrgVOById(String id) {
        return this.getOrgAndParentOrgByOrgId(id);
    }

    /**
     * 返回机构树，非超级管理员只返回自己租户的数据
     * @param tenantId
     * @return
     * @throws Exception
     */
    @Override
	@Cacheable(value = "orgs", key = "'allList:' + #tenantId") //缓存
    public List<TreeUtils> getAllOrgTreeUtils(String tenantId) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andTenantIdEqualTo(tenantId);
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", null, null);
        return treeList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'orgTreeIncludeDeptByParentId:' + #parentId") //缓存
    public List<TreeUtils> getOrgsTreeUtilsIncludeDeptByParentId(String parentId) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", "orgRank", null, null);
        return treeList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'orgTreeIncludeDeptById:' + #id") //缓存
    public List<TreeUtils> getOrgsTreeUtilsIncludeDeptById(String id) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", "orgRank", null, null);
        return treeList;
    }

    /**查询自己所在机构*/
    @Override
    @Cacheable(value = "orgs", key = "'orgTreeExcludeDeptById:' + #id") //缓存
    public List<TreeUtils> getOrgsTreeUtilsExcludeDeptById(String id) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andOrgRankEqualTo("1");
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", "orgRank", null, null);
        return treeList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'orgTreeExcludeDeptByParentId:' + #parentId") //缓存
    public List<TreeUtils> getOrgsTreeUtilsExcludeDeptByParentId(String parentId) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        criteria.andOrgRankEqualTo("1");
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", "orgRank", null, null);
        return treeList;
    }


    /**
     * 返回机构树，超级管理员只返回全部的数据
     * @return
     * @throws Exception
     */
    @Override
//	@Cacheable(value = "orgs", key = "'allList'") //缓存
    @Cacheable(value = "orgs", key = "'getAllOrgTreeUtils'") //缓存
    public List<TreeUtils> getAllOrgTreeUtils() throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", null, null);
        return treeList;
    }

    /**
     * 新增机构信息
     * @param org
     * @param userVO
     */
    @Override
	@CacheEvict(value="orgs",allEntries=true)
    @Transactional(rollbackFor = Exception.class)
    public void addOrg(Org org, UserVO userVO) throws Exception {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(org.getOrgCode());
        List<Org> list = orgMapper.selectByExample(example);
        if (!list.isEmpty()) {
            if (Constant.OrgRank.ORGRANK_COMPANY.getValue().equals(org.getOrgRank())) {
                throw new BusinessException("统一社会信用代码已存在{" + org.getId() + ":" + org.getOrgName() + "}");
            }
        }
        OrgExample orgNameCheckExample = new OrgExample();
        OrgExample.Criteria orgNameCheckCriteria = orgNameCheckExample.createCriteria();
        orgNameCheckCriteria.andParentIdEqualTo(org.getParentId());
        orgNameCheckCriteria.andOrgNameEqualTo(org.getOrgName());
        orgNameCheckCriteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        List<Org> listName = orgMapper.selectByExample(orgNameCheckExample);
        if (!listName.isEmpty()) {
            throw new BusinessException("机构名称不允许重复{" + org.getParentId() + ":" + org.getOrgName() + "}");
        }
        Date nowDate = new Date();
        if (org.getParentId() == null || "".equals(org.getParentId())) {
            //没有上级的将上级编号设置为0，将级别设置为1
            org.setOrgLevel(1);
            org.setParentId("0");
        }
        if (!"0".equals(org.getParentId())) {
            //将上级isParent 设置为1，即是父节点
            Org parent = orgMapper.selectByPrimaryKey(org.getParentId());
            if (parent != null) {
                parent.setIsParent(Constant.COMMON_YES_OR_NO_YES);
                org.setOrgLevel(parent.getOrgLevel() + 1);
                org.setTenantId(parent.getTenantId());
                orgMapper.updateByPrimaryKey(parent);
            }
        }
        if (Constant.OrgRank.ORGRANK_DEPT.getValue().equals(org.getOrgRank()) && StringUtils.isBlank(org.getOrgCode())) {
            try {
                org.setOrgCode(codeUseInfoService.getOne("SYS-DEPTCODE", null));
            } catch (Exception e) {
                throw new BusinessException("生成部门编码失败，请稍后重试");
            }
        }
        if (org.getId() == null) {
            org.setId(UuidUtil.get32UUID());
        }
        if (org.getIsParent() == null) {
            org.setIsParent(Constant.COMMON_YES_OR_NO_NO);
        }
        org.setVersion(0);
        org.setCreater(userVO.getId());
        if (org.getCreateTime() == null) {
            org.setCreateTime(nowDate);
        }
        org.setModUser(userVO.getId());
        org.setModTime(nowDate);
        if (org.getType() == null) {
            org.setType("1"); //本系统维护
        }
        orgMapper.insert(org);

        //资金结算，自动创建核算户信息
        /*Map<String, Object> map = new HashMap<>();
        List<FundAccountingInfo> accountingList = new ArrayList();
        FundAccountingInfo accountingInfo = new FundAccountingInfo();
        Map codeParams = new HashMap();
        codeParams.put("op", "getOne");
        codeParams.put("code", "ZJJS-HSH");
        codeParams.put("param", org.getOrgCode());
        R codeR = codeUseInfoController.codeTest(codeParams);
        accountingInfo.setAccountingNo(codeR.get("str").toString());
        accountingInfo.setEntId(org.getOrgCode());
        accountingInfo.setEntName(org.getOrgName());
        accountingInfo.setCurrency("01");
        accountingList.add(accountingInfo);
        map.put("accountingList", accountingList);
        fundAccountingFeign.saveOrUpdateAccounting(map);*/
    }

    /**
     * 修改机构信息
     * @param org
     * @param userVO
     */
    @Override
    @CacheEvict(value = "orgs", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateOrg(Org org, UserVO userVO) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(org.getOrgCode());
        criteria.andIdNotEqualTo(org.getId());
        List<Org> list = orgMapper.selectByExample(example);
        if (!list.isEmpty()) {
            if (Constant.OrgRank.ORGRANK_COMPANY.getValue().equals(org.getOrgRank())) {
                throw new BusinessException("统一社会信用代码已存在");
            } else {
                throw new BusinessException("编码已存在");
            }
        }
        OrgExample orgNameCheckExample = new OrgExample();
        OrgExample.Criteria orgNameCheckCriteria = orgNameCheckExample.createCriteria();
        orgNameCheckCriteria.andParentIdEqualTo(org.getParentId());
        orgNameCheckCriteria.andOrgNameEqualTo(org.getOrgName());
        orgNameCheckCriteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        orgNameCheckCriteria.andIdNotEqualTo(org.getId());
        List<Org> listName = orgMapper.selectByExample(orgNameCheckExample);
        if (!listName.isEmpty()) {
            throw new BusinessException("机构名称不允许重复{" + org.getParentId() + ":" + org.getOrgName() + "}");
        }
        Date nowDate = new Date();
        Org orgNew = orgMapper.selectByPrimaryKey(org.getId());
        Org parent = orgMapper.selectByPrimaryKey(org.getParentId());
        if (parent != null) {
            //根据上级级别重新设置当前级别
            orgNew.setOrgLevel(parent.getOrgLevel() + 1);
        }
        orgNew.setVersion(orgNew.getVersion() + 1);
        orgNew.setModTime(nowDate);
        orgNew.setModUser(userVO.getUsername());
        orgNew.setOrdernum(org.getOrdernum());
        orgNew.setOrgName(org.getOrgName());
        orgNew.setShortName(org.getShortName());
        orgNew.setOrgStatus(org.getOrgStatus());
        orgNew.setOrgType(org.getOrgType());
        orgNew.setOrgRank(org.getOrgRank());
        orgNew.setOrgCode(org.getOrgCode());
        orgNew.setOrgGrade(org.getOrgGrade());
        orgNew.setParentId(org.getParentId());
        orgMapper.updateByPrimaryKey(orgNew);
    }

    /**
     * 删除机构信息
     * @param id
     * @param userVO
     */
    @Override
    @CacheEvict(value = "orgs", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id, UserVO userVO) {
        // 删除机构下挂的岗位、岗位权限、岗位用户信息
       /* StationExample stationExample = new StationExample();
        StationExample.Criteria criteriaStation = stationExample.createCriteria();
        criteriaStation.andOrgIdEqualTo(id);
        List<Station> stations = stationMapper.selectByExample(stationExample);
        List<String> stationIds = getStationIds(stations);
        if (!stationIds.isEmpty()) {
            stationMapper.deleteByExample(stationExample);
            StationMenuExample stationMenuExample = new StationMenuExample();
            StationMenuExample.Criteria criteriaStationMenu = stationMenuExample.createCriteria();
            criteriaStationMenu.andStationIdIn(stationIds);
            stationMenuMapper.deleteByExample(stationMenuExample);
            UserStationExample userStationExample = new UserStationExample();
            UserStationExample.Criteria criteriaUserStation = userStationExample.createCriteria();
            criteriaUserStation.andStationIdIn(stationIds);
            userStationMapper.deleteByExample(userStationExample);
        }*/
        //逻辑删除
        Org org = orgMapper.selectByPrimaryKey(id);
        org.setOrgStatus(Constant.COMMON_STATUS_DELETED);
        org.setModUser(userVO.getId());
        org.setModTime(new Date());
        orgMapper.updateByPrimaryKey(org);
//        orgMapper.deleteByPrimaryKey(id);
    }


    private List<String> getStationIds(List<Station> stations) {
        List<String> ids = new ArrayList<String>();
        for (Station station : stations) {
            ids.add(station.getId());
        }
        return ids;
    }


    @Override
    public void initOrg() {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause(" ordernum ");
        List<Org> list = orgMapper.selectByExample(example);
//        System.out.println("数据列表个数 " + list.size());
        for (int i = 0; i < list.size(); i++) {
            Org org1 = list.get(i);
            ;
            if (org1.getOrgCode().length() > 4) {
                //插入部门
                Org org = new Org();
                org.setId(UuidUtil.get32UUID());
                org.setOrgCode(org1.getOrgCode() + "dp01");
                org.setOrgName("业务部");
                org.setShortName("业务部");
                org.setTenantId("1");
                org.setParentId(org1.getId());
                org.setOrgStatus("1");
                org.setIsParent("1");
                org.setOrgType("1");
                org.setOrgRank("2");
                org.setOrdernum(1);
                orgMapper.insert(org);
                Org org2 = new Org();
                org2.setId(UuidUtil.get32UUID());
                org2.setOrgCode(org1.getOrgCode() + "dp02");
                org2.setOrgName("财务部");
                org2.setShortName("财务部");
                org2.setParentId(org1.getId());
                org2.setTenantId("1");
                org2.setOrgStatus("1");
                org2.setIsParent("1");
                org2.setOrgType("1");
                org2.setOrgRank("2");
                org2.setOrdernum(2);
                orgMapper.insert(org2);
                Org org3 = new Org();
                org3.setId(UuidUtil.get32UUID());
                org3.setOrgCode(org1.getOrgCode() + "dp03");
                org3.setOrgName("法律部");
                org3.setShortName("法律部");
                org3.setParentId(org1.getId());
                org3.setTenantId("1");
                org3.setOrgStatus("1");
                org3.setIsParent("1");
                org3.setOrgType("1");
                org3.setOrgRank("2");
                org3.setOrdernum(3);
                orgMapper.insert(org3);

            }
        }
    }

    /**
     * @功能描述: 更新机构级别
     * @auther: jiaozhongcai
     * @date: 2021/6/3 16:18
     * @param
     * @return: null
     */
    @Override
    public void updateorgLevel() {
        List<Org> list = orgMapper.selectCodeAndLength();
        for (int i = 0; i < list.size(); i++) {
            Org org = list.get(i);
            Org orgLevel = new Org();
            orgLevel.setOrgCode(org.getOrgCode());
            orgLevel.setOrgLevel(org.getOrgLevel());
            orgMapper.updateOrgLeave(orgLevel);
        }
    }

    /**
     * @功能描述: 根据所在部门id 查询所属机构的机构信息
     * @auther: jiaozhongcai
     * @date: 2021/6/9 13:46
     * @param orgId
     * @return: String
     */
    @Override
    public List<Org> getParentOrgByOrgId(String orgId) {
        return orgMapper.getParentOrgByOrgId(orgId);
    }


    @Override
    public Org selectById(String id) {
        return orgMapper.selectByPrimaryKey(id);
    }

    @Override
    public Org selectByOrgCode(String orgCode) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(orgCode);
        List<Org> orgs = orgMapper.selectByExample(example);
        if (orgs.size() > 0) {
            return orgs.get(0);
        }
        return null;
    }


    /**
     * @功能描述: 根据机构code，返回机构下部门id
     * @auther: jiaozhongcai
     * @date: 2021/6/8 14:52
     * @param orgCode
     * @param type
     * @return: String
     */
    public String getOrgId(String orgCode, String type) {
        String id = "";
        if ("1".equals(type)) { //财务用户
            orgCode = orgCode + "dp02";
        } else {
            orgCode = orgCode + "dp01";
        }
        Org orgIdCode = orgMapper.getOrgIdCode(orgCode);

        return org.springframework.util.ObjectUtils.isEmpty(orgIdCode) ? "" : orgIdCode.getId();

    }

    public String getPassword(String username, String salt) {
        String password = passwordExpired.getDefaultPassword();
        salt = username + salt;
        int hashIterations = 2;
        SimpleHash simpleHash = new SimpleHash("md5", password, ByteSource.Util.bytes(salt), hashIterations);
//        System.out.println("密码结果= " + simpleHash.toHex());
        return simpleHash.toHex();
    }

    /**
     * @param
     * @功能描述: 获取当前登录人所属企业及上级企业信息
     * @auther: 田炜俊
     * @return: EntAndUpperEntVo
     */
    @Override
    public EntAndUpperEntVo getEntAndUpperEntInfo(UserVO user) {
        EntAndUpperEntVo entAndUpperEntVo = new EntAndUpperEntVo();
        EntVo entVoByUserId = orgMapper.getEntVoByUserId(user.getOrgId());
        EntVo upperEntVoByOrgId = orgMapper.getUpperEntVoByOrgId(entVoByUserId.getId());
        //判断如果机构编码为企业
        if ("1".equals(entVoByUserId.getEntRank())) {
            entAndUpperEntVo.setId(entVoByUserId.getId());
            entAndUpperEntVo.setEntId(entVoByUserId.getEntId());
            entAndUpperEntVo.setEntLevel(entVoByUserId.getEntLevel());
            entAndUpperEntVo.setEntName(entVoByUserId.getEntName());
            entAndUpperEntVo.setEntRank(entVoByUserId.getEntRank());
            if (StringUtils.isNotBlank(upperEntVoByOrgId)) {
                entAndUpperEntVo.setUpperId(upperEntVoByOrgId.getId());
                entAndUpperEntVo.setUpperEntLevel(upperEntVoByOrgId.getEntLevel());
                entAndUpperEntVo.setUpperEntId(upperEntVoByOrgId.getEntId());
                entAndUpperEntVo.setUpperEntName(upperEntVoByOrgId.getEntName());
                entAndUpperEntVo.setUpperEntRank(upperEntVoByOrgId.getEntRank());
            }

        } else {//如果机构编码为部门
            if (StringUtils.isNotBlank(upperEntVoByOrgId.getId())) {
                EntVo upperEntVo = orgMapper.getUpperEntVoByOrgId(upperEntVoByOrgId.getId());
                entAndUpperEntVo.setId(upperEntVoByOrgId.getId());
                entAndUpperEntVo.setEntId(upperEntVoByOrgId.getEntId());
                entAndUpperEntVo.setEntLevel(upperEntVoByOrgId.getEntLevel());
                entAndUpperEntVo.setEntName(upperEntVoByOrgId.getEntName());
                entAndUpperEntVo.setEntRank(upperEntVoByOrgId.getEntRank());
                if (StringUtils.isNotBlank(upperEntVo)) {
                    entAndUpperEntVo.setUpperId(upperEntVo.getId());
                    entAndUpperEntVo.setUpperEntLevel(upperEntVo.getEntLevel());
                    entAndUpperEntVo.setUpperEntId(upperEntVo.getEntId());
                    entAndUpperEntVo.setUpperEntName(upperEntVo.getEntName());
                    entAndUpperEntVo.setUpperEntRank(upperEntVo.getEntRank());
                }
            }
        }
        entAndUpperEntVo.setDeptId(user.getDefaultOrg().getOrgCode());
        List<EntVo> lowerEntVosByOrgId = orgMapper.getLowerEntVosByOrgId(entAndUpperEntVo.getId());
        entAndUpperEntVo.setLastLevel(StringUtils.isBlank(lowerEntVosByOrgId) ? true : lowerEntVosByOrgId.size() > 0 ? false : true);
        return entAndUpperEntVo;
    }

    /**
     * @param
     * @功能描述: 获取企业信息
     * @auther: 田炜俊
     * @return: EntAndUpperEntVo
     */
    @Override
    public PageUtils queryPageEntInfoList(Map<String, Object> params) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
//        Session session = SecurityUtils.getSubject().getSession();
//        User user = (User) session.getAttribute(Constant.USERSESSION);
//        UserVO userVO = (UserVO) redisTemplate.opsForValue().get(Constant.REDIS_PREFIX + user.getId());
        UserVO userVO = UserUtil.getUser();
        EntAndUpperEntVo entAndUpperEntVo = getEntAndUpperEntInfo(userVO);

        PageUtils pageUtils = PageUtils.getPageInfo(jsonObject);
        Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());

        if (StringUtils.isNotBlank(jsonObject.get("queryType"))) {
            String type = jsonObject.getString("queryType");
            if ("lower".equals(type)) {
                jsonObject.put("entId", entAndUpperEntVo.getEntId());
                if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
                    jsonObject.put("orgName", "%" + jsonObject.get("orgName").toString() + "%");
                } else {
                    jsonObject.put("orgName", "");
                }
                if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
                    jsonObject.put("orgCode", "%" + jsonObject.get("orgCode").toString() + "%");
//                    List<Org> orgs = orgMapper.getCurrentAndChildrenOrgListHasOrgCode(jsonObject);
                }
                List<Org> orgs = orgMapper.getCurrentAndChildrenOrgList(jsonObject);
                pageUtils = new PageUtils(p);
            }
        } else {
            //查找全部或上级
            /*OrgExample example = new OrgExample();
            OrgExample.Criteria criteria = example.createCriteria();
            example.setOrderByClause("org_code");
            criteria.andOrgRankEqualTo("1");
            if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
                String enterpiseId = jsonObject.getString("orgCode");
                criteria.andOrgCodeLike("%" + enterpiseId + "%");
            }
            if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
                String enterpiseName = jsonObject.getString("orgName");
                criteria.andOrgNameLike("%" + enterpiseName + "%");
            }
            criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
            List<Org> orgs = orgMapper.selectByExample(example);
            */
            if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
                jsonObject.put("orgName", "%" + jsonObject.get("orgName").toString() + "%");
            } else {
                jsonObject.put("orgName", "");
            }
            jsonObject.put("orgCode", jsonObject.get("orgCode").toString());
            List<Org> orgs = orgMapper.getCurrentAndChildrenOrgListHasOrgCode(jsonObject);
            pageUtils = new PageUtils(p);
        }


        return pageUtils;
    }

    /**
     * @param
     * @功能描述: 获取当前登录人及其下属各级企业编码
     * @auther: 田炜俊
     * @return: List<String>
     */
    @Override
    public Set<String> getCurrentAndChildrenEntCodeList(UserVO user) {
        EntAndUpperEntVo entAndUpperEntInfo = getEntAndUpperEntInfo(user);
        Set<String> set = orgMapper.getCurrentAndChildrenOrgCodeList(entAndUpperEntInfo.getEntId());
        return set;
    }

    @Override
    public List<Org> getOrgListByOrgName(Map<String, String> params) {
        /*OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("org_code");
        criteria.andOrgRankEqualTo("1");
        //增加数据权限控制
        UserVO userVO = UserUtil.getUser();
        criteria.andOrgCodeLike(userVO.getOrg().getParentOrg().getOrgCode() + "%");
        //TODO
        if (StringUtils.isNotBlank(params.get("orgName"))) {
            criteria.andOrgNameLike("%" + params.get("orgName") + "%");
        }
        List<Org> orgs = orgMapper.selectByExample(example);*/
        UserVO userVO = UserUtil.getUser();
        Map<String, Object> param = new HashMap<>();
        String oId = configService.getParamVlueByKey("GcorgID").getParamValue();
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo("0");
        List<Org> list = orgMapper.selectByExample(example);
        if (userVO.getUsername().equals(Constant.ADMIN)) {//超管
            if (!list.isEmpty()) {
                oId = list.get(0).getId();
            }
            param.put("id", oId);
        } else {//不是超管，先查询出所在机构(当前管理的机构）
            if (Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())) {
                //如果是部门
                if (Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())) {
                    //上级如果是虚拟机构（本部）则找爷爷
                    param.put("id", userVO.getDefaultOrg().getGrandpa().getId());
                } else {
                    //上级如果是实体
                    param.put("id", userVO.getDefaultOrg().getParentOrg().getId());
                }
            } else {
                if (Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())) {
                    //如果是虚拟机构（本部）则找爸爸
                    param.put("id", userVO.getDefaultOrg().getParentOrg().getId());
                } else {
                    //上级如果是实体
                    param.put("id", userVO.getDefaultOrg().getId());
                }
            }
        }
        /*if(Constant.OrgRank.ORGRANK_COMPANY.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
            param.put("id", userVO.getDefaultOrg().getId());
        }else{

            param.put("id", userVO.getDefaultOrg().getParentId());
        }*/
        param.put("orgName", "%" + params.get("orgName") + "%");
        if (StringUtils.isNotBlank(params.get("orgRank")))
            param.put("orgRank", params.get("orgRank"));
        String status = null;
        if (params.containsKey("status")){
            //查询外企不设数据权限
            param.put("id", oId);
            status = params.get("status");
        }
        param.put("status",status);
        List<Org> orgs = orgMapper.getOrgListByOrgNameRight(param);
        return orgs;
    }

    @Override
    public List<Org> getOrgListByOrgName2(Map<String, String> params) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("org_code");
        criteria.andOrgRankEqualTo("1");
        criteria.andOrgStatusNotEqualTo("100103");
        //增加数据权限控制
//        UserVO userVO = (UserVO) redisTemplate.opsForValue().get(Constant.REDIS_PREFIX + UserUtil.getUser().getId());
//        criteria.andOrgCodeLike(userVO.getOrgCode() + "%");
        if (StringUtils.isNotBlank(params.get("orgName"))) {
            criteria.andOrgNameLike("%" + params.get("orgName") + "%");
        }
        List<Org> orgs = orgMapper.selectByExample(example);

        return orgs;
    }

    @Override
    public List<Org> getOrgListByParams(Map params) {
        String orgId = params.get("orgId").toString();
        List<Org> orgList = new ArrayList<>();
        if (StringUtils.isNotBlank(orgId)) {
            Org org = orgMapper.selectByPrimaryKey(orgId);
            Set<Org> branchVOSet = new HashSet<>();
            branchVOSet.add(org);
            branchVOSet = buildTreeUp(org, branchVOSet);
            Iterator<Org> it = branchVOSet.iterator();
            while (it.hasNext()) {
                orgList.add(it.next());
            }
            Collections.sort(orgList, new Comparator<Org>() {
                @Override
                public int compare(Org o1, Org o2) {
                    return o2.getOrgCode().compareTo(o1.getOrgCode());
                }
            });
        }
        Collections.reverse(orgList);
        return orgList;
    }

    @Override
    public List<TreeUtils> getOrgsTreeUtilsIncludeByParams(Map params) throws Exception {
        String parentId = params.get("parentId").toString();
        String orgRank = params.get("orgRank").toString();
        Boolean isAllOrg = (boolean) params.get("isAllOrg");
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(orgRank)) {
            criteria.andOrgRankEqualTo("1");
        }
        example.setOrderByClause(" ordernum ");
        List<Org> list = null;
        List<TreeUtils> treeList = null;

        //查询所有组织机构
        if (isAllOrg) {
            parentId = "".equals(parentId) ? "0" : parentId;
            criteria.andParentIdEqualTo(parentId);
            if (!params.containsKey("status")){
                criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
            }
//            list = orgMapper.selectByExample(example);

        } else {
            //登陆者是管理员
            UserVO userVO = UserUtil.getUser();
            if (userVO.getUsername().equals(Constant.ADMIN)) {
                parentId = "".equals(parentId) ? "0" : parentId;
                criteria.andParentIdEqualTo(parentId);
            } else if (!userVO.getUsername().equals(Constant.ADMIN) && "0".equals(parentId)) {//不是超管，先查询出所在机构

                if (Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())) {
                    //如果是部门
                    if (Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())) {
                        //上级如果是虚拟机构（本部）则找爷爷
                        criteria.andIdEqualTo(userVO.getDefaultOrg().getGrandpa().getId());
                    } else {
                        //上级如果是实体
                        criteria.andIdEqualTo(userVO.getDefaultOrg().getParentOrg().getId());
                    }
                } else {
                    if (Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())) {
                        //如果是虚拟机构（本部）则找爸爸
                        criteria.andIdEqualTo(userVO.getDefaultOrg().getParentOrg().getId());
                    } else {
                        //上级如果是实体
                        criteria.andIdEqualTo(userVO.getDefaultOrg().getId());
                    }
                }
            } else { //非超管的下一级机构或部门
                criteria.andParentIdEqualTo(parentId);
            }
            if (!params.containsKey("status")){
                criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
            }
        }
        list = orgMapper.selectByExample(example);
        treeList = TreeUtils.getTreeList(list, "id", "parentId", "orgName", "orgRank", null, null);
        return treeList;
    }

    @Override
    public List<Org> getOrgListByOrgCode(String orgCode) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("org_code");
        if (StringUtils.isNotBlank(orgCode)) {
            criteria.andOrgCodeEqualTo(orgCode);
        }
        List<Org> orgs = orgMapper.selectByExample(example);
        return orgs;
    }

    @Override
    @Cacheable(value = "orgs", key = "'getOrgAndLowerOrgInfoByOrgCode:' + #params.get('orgCode')") //缓存
    public List<Map<String, Object>> getOrgAndLowerOrgInfoByOrgCode(Map<String, Object> params) {
        String orgCode = (String) params.get("orgCode");
        List<Map<String, Object>> mapList = new ArrayList<>();
        mapList = orgMapper.getCurrentAndChildrenOrgInfoListByOrgCode(orgCode);
        return mapList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'getOrgAndParentOrgByOrgId:' + #deptId") //缓存
    public OrgVO getOrgAndParentOrgByOrgId(String deptId) {
        Org dept = this.selectById(deptId);
        if (dept == null) {
            return new OrgVO();
        }
        Org org = this.selectById(dept.getParentId());
        Org grandpa = this.selectById(org != null ? org.getParentId() : null);
        OrgVO orgVo = new OrgVO();
        BeanUtils.copyProperties(dept, orgVo);
        orgVo.setParentOrg(org);
        orgVo.setGrandpa(grandpa);
        return orgVo;
    }

    @Override
    public OrgVO getDefaultOrgByUserId(String userId) {
        UserMngOrg defaultOrg = sysUserMngOrgService.getDefaultMngOrgByUserId(userId);
        return this.getOrgAndParentOrgByOrgId(defaultOrg.getOrgId());
    }

    @Override
    public OrgVO getOrgAndParentOrgByOrgCode(String orgCode) {
        Org dept = this.selectByOrgCode(orgCode);
        Org org = this.selectById(dept.getParentId());
        OrgVO orgVo = new OrgVO();
        BeanUtils.copyProperties(dept, orgVo);
        orgVo.setParentOrg(org);
        return orgVo;
    }

    @Override
    public List<OrgVO> getMngDeptByUserId(String userId) {
        List<OrgVO> deptVos = new ArrayList<>();
        List<UserMngOrg> userMngOrgs = sysUserMngOrgService.getListByUserId(userId);
        for (UserMngOrg userMngOrg : userMngOrgs) {
            OrgVO deptVo = this.getOrgAndParentOrgByOrgId(userMngOrg.getOrgId());
            deptVo.setDefaultState(userMngOrg.getDefaultState());
        }
        return null;
    }

    @Override
    public PageUtils queryPageGradeOneAndChildOrg(Map<String, Object> params, UserVO user) {
        OrgVO defaultOrg = user.getDefaultOrg();
        Org topOrg = null;
        if (defaultOrg.getParentOrg().getOrgGrade().equals("0")) {
            topOrg = defaultOrg.getParentOrg();
        } else {
            topOrg = this.getGradeOneOrgByOrgId(defaultOrg.getParentId());
        }
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());

        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeLike(topOrg.getOrgCode() + "%");
        criteria.andOrgRankEqualTo("1");
        if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
            String enterpiseId = jsonObject.getString("orgCode");
            criteria.andOrgCodeLike("%" + enterpiseId + "%");
        }
        if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
            String enterpiseName = jsonObject.getString("orgName");
            criteria.andOrgNameLike("%" + enterpiseName + "%");
        }
        example.setOrderByClause("org_code");
        List<Org> orgs = orgMapper.selectByExample(example);
        pageUtils = new PageUtils(p);

        return pageUtils;
    }

    @Override
    public Org getGradeOneOrgByOrgCode(String orgCode) {
        Org org = this.getOrgByOrgCode(orgCode);
        return this.getGradeOneOrgByOrgId(org.getId());
    }


    @Override
    public Org getGradeOneOrgByOrgId(String orgId) {
        Org org = this.selectById(orgId);
        if ("1".equals(org.getOrgGrade())) {
            return org;
        } else {
            return getGradeOneOrgByOrgId(org.getParentId());
        }
    }

    @Override
    public PageUtils queryPageOrgAndChildOrg(Map<String, Object> params, UserVO user) {
        OrgVO defaultOrg = user.getDefaultOrg();
        Org topOrg = defaultOrg.getParentOrg();
        if (topOrg.getOrgType().equals("1") && topOrg.getOrgRank().equals("1")) {
            topOrg = user.getDefaultOrg().getGrandpa();
        }
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
//        criteria.andOrgCodeLike(topOrg.getOrgCode() + "%");
        criteria.andOrgRankEqualTo("1");
        criteria.andOrgTypeEqualTo("2");
        OrgExample.Criteria criteriaTwo = example.createCriteria();
        criteriaTwo.andOrgRankEqualTo("1");
        criteriaTwo.andOrgTypeEqualTo("2");
        if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
            String enterpiseId = jsonObject.getString("orgCode");
            criteriaTwo.andOrgCodeLike("%" + enterpiseId + "%");
            criteria.andOrgCodeLike("%" + enterpiseId + "%");
        } else {
            criteriaTwo.andIdEqualTo(topOrg.getId());
        }
        if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
            String enterpiseName = jsonObject.getString("orgName");
            criteriaTwo.andOrgNameLike("%" + enterpiseName + "%");
            criteria.andOrgNameLike("%" + enterpiseName + "%");
        } else {
            criteriaTwo.andIdEqualTo(topOrg.getId());
        }
        criteria.andParentIdEqualTo(topOrg.getId());
        example.or(criteriaTwo);
        example.setOrderByClause("org_code");
        List<Org> orgs = orgMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    @Override
    public PageUtils queryOneOrgAll(Map<String, Object> params, UserVO user) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgRankEqualTo("1");//扩展级别，例如：1-公司、2-部门、9-其他
        criteria.andOrgStatusEqualTo("100101");//机1构状态:100101-正常 100102-暂停
        criteria.andOrgTypeEqualTo("2"); // 机构分类：1-虚拟机构、2-实体机构
        if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
            String enterpiseId = jsonObject.getString("orgCode");
            criteria.andOrgCodeLike("%" + enterpiseId + "%");
        }
        if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
            String enterpiseName = jsonObject.getString("orgName");
            criteria.andOrgNameLike("%" + enterpiseName + "%");
        }
        example.setOrderByClause("org_code");
        List<Org> orgs = orgMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    @Override
    public List<Org> queryOneOrgList(Map<String, Object> params, UserVO user) {
        JSONObject jsonObject = JSONObject.fromObject(params);
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria criteria = orgExample.createCriteria();
        if (StringUtils.isNotBlank(jsonObject.get("orgCode")) && StringUtils.isNotBlank(jsonObject.get("orgName"))) {
            criteria.andOrgCodeEqualTo(jsonObject.getString("orgCode"));
            criteria.andOrgNameEqualTo(jsonObject.getString("orgName"));
        } else {
            throw new BusinessException("请传入单位名称和单位编号.");
        }
        Org org = Optional.ofNullable(orgMapper.selectByExample(orgExample)).orElseGet(ArrayList::new).stream().findFirst().orElse(null);
        if (org != null) {
            OrgExample orgExampleTwo = new OrgExample();
            orgExampleTwo.createCriteria()
                    .andParentIdEqualTo(org.getId())
                    .andOrgRankEqualTo("1")
                    .andOrgStatusEqualTo("100101")
                    .andOrgTypeEqualTo("2");
            List<Org> orgs = orgMapper.selectByExample(orgExampleTwo);
            orgs.add(orgs.size(), org);
            return orgs;
        } else {
            return null;
        }
    }


    /**
     * @param
     * @功能描述:根据单位编码查询部门信息
     * @return: params
     */
    @Override
    @Cacheable(value = "orgs", key = "'findOrgUpList:' + #params.get('orgCode')") //缓存
    public List<Org> findOrgUpList(Map<String, Object> params) {
        List<Org> orgList = new ArrayList<>();
        if (StringUtils.isNotBlank(params.get("orgCode"))) {
            OrgExample orgExample = new OrgExample();
            orgExample.createCriteria().andOrgCodeEqualTo(String.valueOf(params.get("orgCode")));
            Org org = Optional.ofNullable(orgMapper.selectByExample(orgExample)).orElseGet(ArrayList::new).stream().findFirst().orElse(null);
            if (org != null && StringUtils.isNotBlank(org.getParentId())&&!org.getParentId().equals("0")) {
                orgList = findOrgUpListAll(org, orgList);
            }
            orgList.add(org);
        } else {
            return orgList;
        }
        return orgList.stream().distinct().collect(Collectors.toList());
    }

    //递归查找上级 一直查到集团为止
//    @Cacheable(value = "orgs", key = "'findOrgUpListAll:' + #org.id") //缓存
    public List<Org> findOrgUpListAll(Org org, List<Org> orgList) {
        OrgExample orgExample = new OrgExample();
        orgExample.createCriteria().andIdEqualTo(org.getParentId());
        Org parentOrg = Optional.ofNullable(orgMapper.selectByExample(orgExample)).orElseGet(ArrayList::new).stream().findFirst().orElse(null);
        if (parentOrg != null && StringUtils.isNotBlank(parentOrg.getParentId())) {
            orgList.add(parentOrg);
            if (!parentOrg.getParentId().equals("0")) {
                findOrgUpListAll(parentOrg, orgList);
            }
        }
        return orgList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'findOrgDeptList:' + #params.get('orgCode')") //缓存
    public List<Org> findOrgDeptList(Map<String, Object> params) {
        //查询的传进来的org信息
        OrgExample orgExample = new OrgExample();
        orgExample.createCriteria().andOrgCodeEqualTo(String.valueOf(params.get("orgCode")));
        Org org = Optional.ofNullable(orgMapper.selectByExample(orgExample)).orElseGet(ArrayList::new).stream().findFirst().orElse(null);
        if (org != null && StringUtils.isNotBlank(org.getId())) {
            //查询单位的本部信息
            OrgExample example = new OrgExample();
            example.createCriteria().andParentIdEqualTo(org.getId()).andOrgTypeEqualTo("1").andOrgRankEqualTo("1");
            Org orgdown = Optional.ofNullable(orgMapper.selectByExample(example)).orElseGet(ArrayList::new).stream().findFirst().orElse(null);
            //查询本部信息下的所有部门机构
            if (orgdown != null && StringUtils.isNotBlank(orgdown)) {
                OrgExample exampleTwo = new OrgExample();
                exampleTwo.createCriteria().andParentIdEqualTo(orgdown.getId()).andOrgRankEqualTo("2");
                List<Org> orgs = orgMapper.selectByExample(exampleTwo);
                orgs.add(orgdown);
                return orgs;
            }
        }
        return null;
    }


    @Override
    @Cacheable(value = "orgs", key = "'getOrgByOrgCodeAll:' + #orgCode") //缓存
    public List<Org> getOrgByOrgCodeAll(String orgCode) {
        List<String> listByOrgCode = getCurrentAndBelowOrgCodeListByOrgCode(orgCode);
        OrgExample orgExample1 = new OrgExample();
        orgExample1.createCriteria().andOrgCodeEqualTo(orgCode);
        Org org = orgMapper.selectByExample(orgExample1).stream().findFirst().orElse(null);
        List<Org>orgList=new ArrayList<>();
        if (org!=null){
            OrgExample orgExample = new OrgExample();
            OrgExample.Criteria criteria = orgExample.createCriteria();
            criteria.andOrgTypeEqualTo("2");
            criteria.andOrgRankEqualTo("1");
            criteria.andParentIdEqualTo(org.getId());
            orgList = orgMapper.selectByExample(orgExample);
        }
        orgList.add(org);
        return orgList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'getOrgByOrgCodeDownAll:' + #orgCode") //缓存
    public List<Org> getOrgByOrgCodeDownAll(String orgCode) {
        List<String> listByOrgCode = getCurrentAndBelowOrgCodeListByOrgCode(orgCode);
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria criteria = orgExample.createCriteria();
        criteria.andOrgCodeIn(listByOrgCode);
        criteria.andOrgTypeEqualTo("2");
        orgExample.setOrderByClause("org_code");
        List<Org>orgList = orgMapper.selectByExample(orgExample);
        return orgList;
    }

    @Override
    @Cacheable(value = "orgs", key = "'findOrgList:' + #orgCode") //缓存
    public HashMap<String, List<Org>> findOrgList(String orgCode) {
        HashMap<String, List<Org>> map = new HashMap<>();
        List<Org> orgCodeList = getOrgByOrgCodeAll(orgCode);
        List<Org> collect = orgCodeList.stream().filter(org -> !org.getOrgCode().equals(orgCode)).collect(Collectors.toList());
        for (Org org : collect) {
            List<Org> orgByOrgCodeDownAll = getOrgByOrgCodeDownAll(org.getOrgCode());
            map.put(org.getOrgCode(),orgByOrgCodeDownAll);
        }
        return map;
    }
    
    /**
     * 向上查询直至顶级
     *
     * @param orgId 机构id
     * @return OrgHasParent
     */
    @Override
    @Cacheable(value = "orgs", key = "'getOrgListByOrgIdUpHasNoSelfWithTree:' + #orgId") //缓存
    public OrgHasParent getOrgListByOrgIdUpHasNoSelfWithTree(String orgId){
        Map<String, Object> param = new HashMap<>();
        String[] orgIds = new String[]{orgId};
        param.put("orgIds", Arrays.asList(orgIds));
        List<OrgHasParent> list = orgMapper.getOrgListByOrgIdHasParentSelf(param);
        List<OrgHasParent> newList = list.stream().filter(item -> {
            item.setParent(list.stream().filter(e -> e.getId().equals(item.getParentId())).findFirst().orElse(null));
            return item.getId().equals(orgId);
        }).collect(Collectors.toList());
        return newList.isEmpty() ? new OrgHasParent() : newList.get(0);
    }

    /**
     * 分页查询全量机构
     * @param params {
     *                   'page': pageIndex,
     *                   'limit': pageSize,
     *                   'orgCode': orgCode,
     *                   'orgName': orgName,
     * 				     'orgRank': orgRank,
     * 				     'orgStatus': orgStatus,
     * 				     'orgType': orgType,
     *                }
     * @return 分页结果
     */
    @Override
    public PageUtils queryPageAdmin(Map<String, Object> params) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(params.get("orgCode"))) {
            criteria.andOrgCodeLike("%" + params.get("orgCode").toString().trim() + "%");
        }
        if (StringUtils.isNotBlank(params.get("orgName"))) {
            criteria.andOrgNameLike("%" + params.get("orgName").toString().trim() + "%");
        }
        if (StringUtils.isNotBlank(params.get("orgRank"))) {
            criteria.andOrgRankEqualTo(params.get("orgRank").toString());
        }
        if (StringUtils.isNotBlank(params.get("orgStatus"))) {
            criteria.andOrgStatusEqualTo(params.get("orgStatus").toString());
        }
        if (StringUtils.isNotBlank(params.get("orgType"))) {
            criteria.andOrgTypeEqualTo(params.get("orgType").toString());
        }
        example.setOrderByClause("org_code");
        List<Org> list = orgMapper.selectAdminByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /**
     * 将删除状态的机构恢复正常
     * @param id 机构ID
     */
    @Override
    public void rollbackOrg(String id) {
        Org org = new Org();
        org.setId(id);
        org.setOrgStatus(Constant.COMMON_STATUS_NORMAL);
        orgMapper.updateByPrimaryKeySelective(org);
    }

    @Override
    public List<Org> queryOneOrgAllList(Map<String, Object> params, UserVO user) {
        String queryType = params.get("queryType").toString();
        List<Org> orgList = new ArrayList<>();
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if (queryType.equals("1")) {//获取所有机构信息 不包含部门
            criteria.andOrgRankEqualTo("1");//扩展级别，例如：1-公司、2-部门、9-其他
            criteria.andOrgStatusEqualTo("100101");//机1构状态:100101-正常 100102-暂停
            criteria.andOrgTypeEqualTo("2"); // 机构分类：1-虚拟机构、2-实体机构
            example.setOrderByClause("org_code");
            orgList = orgMapper.selectByExample(example);
            Org org = new Org();
            org.setOrgCode("00000000");
            org.setOrgName("其他");
            orgList.add(org);
        } else if (queryType.equals("2")) {//获取当前机构及下级所有机构信息
            //判断当前单位是否是
            Org parentOrg = UserUtil.getUser().getDefaultOrg().getParentOrg();
            if (parentOrg.getOrgRank().equals("1") && parentOrg.getOrgType().equals("1")) {
                Org grandpa = UserUtil.getUser().getDefaultOrg().getGrandpa();
                List<String> listByOrgCode = getCurrentAndBelowOrgCodeListByOrgCode(grandpa.getOrgCode());
                criteria.andOrgCodeIn(listByOrgCode);
                criteria.andOrgTypeEqualTo("2");
                example.setOrderByClause("org_code");
                orgList = orgMapper.selectByExample(example);
            } else {
                List<String> listByOrgCode = getCurrentAndBelowOrgCodeListByOrgCode(parentOrg.getOrgCode());
                criteria.andOrgCodeIn(listByOrgCode);
                criteria.andOrgTypeEqualTo("2");
                example.setOrderByClause("org_code");
                orgList = orgMapper.selectByExample(example);
            }
            Org org = new Org();
            org.setOrgCode("00000000");
            org.setOrgName("其他");
            orgList.add(org);
        } else if (queryType.equals("3")) {//获取财务公司信息
            criteria.andOrgRankEqualTo("1");//扩展级别，例如：1-公司、2-部门、9-其他
            criteria.andOrgTypeEqualTo("2"); // 机构分类：1-虚拟机构、2-实体机构
            criteria.andOrgStatusEqualTo("100101");//机1构状态:100101-正常 100102-暂停
            criteria.andOrgCodeEqualTo("91110000710934756T");//机1构状态:100101-正常 100102-暂停
            criteria.andOrgNameLike("%" + "财务" + "%");
            example.setOrderByClause("org_code");
            orgList = orgMapper.selectByExample(example);
        } else if (queryType.equals("4")) {//获取集团公司
            criteria.andOrgRankEqualTo("1");//扩展级别，例如：1-公司、2-部门、9-其他
            criteria.andOrgStatusEqualTo("100101");//机1构状态:100101-正常 100102-暂停
            criteria.andParentIdEqualTo("0");
            criteria.andOrgNameLike("%" + "集团" + "%");
            orgList = orgMapper.selectByExample(example);
        }
        return orgList;
    }

    /**
     * 向上递归查询所有父节点（每一层的父节点只有一个）
     * @param org
     * @param branchVOSetSub
     * @return
     */
    private Set<Org> buildTreeUp(Org org, Set<Org> branchVOSetSub) {
        // 向上递归查询所有父节点
        Org sxyBranchVO = orgMapper.selectByPrimaryKey(org.getParentId());
        if (sxyBranchVO != null) { // 如果不是根节点
            branchVOSetSub.add(sxyBranchVO);
            buildTreeUp(sxyBranchVO, branchVOSetSub);
        }

        return branchVOSetSub;
    }

    @Override
    @Cacheable(value = "orgs", key = "'getCurrentAndBelowOrgListByOrgCode:' + #orgCode") //缓存
    public List<Org> getCurrentAndBelowOrgListByOrgCode(String orgCode) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeLike(orgCode + "%");
        criteria.andOrgRankEqualTo("1");

        example.setOrderByClause("org_code");
        List<Org> orgs = orgMapper.selectByExample(example);
        return orgs;
    }

    @Override
    @Cacheable(value = "orgs", key = "'getCurrentAndBelowOrgCodeListByOrgCode:' + #orgCode") //缓存
    public List<String> getCurrentAndBelowOrgCodeListByOrgCode(String orgCode) {
        return orgMapper.getCurrentAndBelowOrgCodeListByOrgCode(orgCode);
    }

    @Override
    public Org getOrgByOrgCode(String orgCode) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(orgCode);
        List<Org> orgs = orgMapper.selectByExample(example);
        if (orgs.size() > 0) {
            return orgs.get(0);
        }
        return null;
    }

    @Override
    public List<OrgHasChildren> selectByExampleHashChildren(Org org) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(org.getId())) {
            criteria.andIdEqualTo(org.getId());
        }
        if (StringUtils.isNotBlank(org.getOrgCode())) {
            criteria.andOrgCodeEqualTo(org.getOrgCode());
        }
        if (StringUtils.isNotBlank(org.getOrgName())) {
            criteria.andOrgNameLike(org.getOrgName());
        }
        if (StringUtils.isNotBlank(org.getParentId())) {
            criteria.andParentIdEqualTo(org.getParentId());
        }
        if (StringUtils.isNotBlank(org.getOrgRank())) {
            criteria.andOrgRankEqualTo(org.getOrgRank());
        }
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        return orgMapper.selectByExampleHashChildren(example);
    }

    /**
     * 根据机构id查询部门（只有部门）
     *
     * @param id
     * @return
     */
    @Override
    public List<Org> queryDeptByParentId(String id) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(id);
        criteria.andOrgRankEqualTo(Constant.OrgRank.ORGRANK_DEPT.getValue());
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        return orgMapper.selectByExample(example);
    }

    @Override
    public List<Org> queryDeptByParentIdAndName(Map<String, Object> params) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(params.get("orgId").toString());
        criteria.andOrgNameEqualTo(params.get("deptName").toString());
        criteria.andOrgRankEqualTo(Constant.OrgRank.ORGRANK_DEPT.getValue());
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        return orgMapper.selectByExample(example);
    }

    /**
     * 根据机构id查询直接下级机构
     *
     * @param id          机构id
     * @param includeDept 是否包含部门
     * @return
     */
    @Override
    @Cacheable(value = "orgs", key = "'queryOrgsByParentId:' + #id + ':' + #includeDept") //缓存
    public List<Org> queryOrgsByParentId(String id, boolean includeDept) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(id);
        if (!includeDept) {
            criteria.andOrgRankEqualTo(Constant.OrgRank.ORGRANK_COMPANY.getValue());
        }
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        return orgMapper.selectByExample(example);
    }

    /**
     * 不包含部门的当前管辖树结构，mybatis嵌套查询性能很差，慎用
     *
     * @param org
     * @return
     */
    @Override
    public List<OrgHasChildren> selectByExampleHashChildrenExcludeDept(Org org) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(org.getId())) {
            criteria.andIdEqualTo(org.getId());
        }
        if (StringUtils.isNotBlank(org.getOrgCode())) {
            criteria.andOrgCodeEqualTo(org.getOrgCode());
        }
        if (StringUtils.isNotBlank(org.getOrgName())) {
            criteria.andOrgNameLike(org.getOrgName());
        }
        if (StringUtils.isNotBlank(org.getParentId())) {
            criteria.andParentIdEqualTo(org.getParentId());
        }
        if (StringUtils.isNotBlank(org.getOrgRank())) {
            criteria.andOrgRankEqualTo(org.getOrgRank());
        }
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        example.setOrderByClause(" ordernum ");
        return orgMapper.selectByExampleHashChildrenExcludeDept(example);
    }

    /**
     * 根据传入id查询机构树
     *
     * @param org
     * @return
     */
    @Override
    @Cacheable(value = "orgs", key = "'selectHashChildrenExcludeDept:' + #org.id + ':' + #org.orgRank") //缓存
    public List<OrgHasChildren> selectHashChildrenExcludeDept(Org org) {
        List<OrgHasChildren> list = orgMapper.queryOrgsListExcludeDeptByParentId(org);
        return list.stream().filter(item -> {
            item.setChildren(list.stream().filter(e -> e.getParentId().equals(item.getId())).collect(Collectors.toList()));
            return item.getId().equals(org.getId());
        }).collect(Collectors.toList());
    }

    /**
     * 获取下一级单位所有部门信息
     * @param id 上级单位id
     * @return
     */
    @Override
    @Cacheable(value = "orgs", key = "'querySonDeptListByParentOrgId:' + #id") //缓存
    public List<Map<String, Object>> querySonDeptListByParentOrgId(String id) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        //首先获取所有下级单位
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria orgCriteria = orgExample.createCriteria();
        orgCriteria.andParentIdEqualTo(id);
        orgCriteria.andOrgRankEqualTo("1");//级别是单位的
        orgCriteria.andOrgStatusEqualTo(Constant.COMMON_STATUS_NORMAL);
        orgExample.setOrderByClause("ordernum");
        List<Org> orgs = orgMapper.selectByExample(orgExample);
        for (Org org : orgs) {
            //获取单位下所有的部门
            OrgExample deptExample = new OrgExample();
            OrgExample.Criteria deptCriteria = deptExample.createCriteria();
            deptCriteria.andParentIdEqualTo(org.getId());
            deptCriteria.andOrgRankEqualTo("2");//级别是单位的
            deptCriteria.andOrgStatusEqualTo(Constant.COMMON_STATUS_NORMAL);
            deptExample.setOrderByClause("ordernum");
            List<Org> deptList = orgMapper.selectByExample(deptExample);
            for (Org dept : deptList) {
                Map<String, Object> map = new HashMap<>();
                map.put("deptId", dept.getId());
                map.put("deptName", dept.getOrgName());
                map.put("entId", org.getId());
                map.put("entName", org.getOrgName());
                mapList.add(map);
            }

        }
        return mapList;
    }

    /**
     * AVIC 应收账款项目
     * 当前登录用户所属机构id，查其下属的所有公司
     * @param org
     */
    @Override
    public List<Org> querySubOrgByParentId(Org org) {

        final OrgExample orgExample = new OrgExample();
        final OrgExample.Criteria criteria = orgExample.createCriteria();
        criteria.andParentIdEqualTo(org.getId());
        criteria.andOrgLevelEqualTo(org.getOrgLevel() + 1);
        return orgMapper.selectByExample(orgExample);

//        return orgMapper.querySubOrgByParentId(org);
    }

    /**
     * 机构迁移
     *
     * @param org
     * @param user
     */
    @Override
    @CacheEvict(value="orgs",allEntries=true)
    public void changeParent(Org org, UserVO user) {
        org.setModUser(user.getId());
        org.setModTime(new Date());
        orgMapper.updateByPrimaryKeySelective(org);
    }

    /**
     * 用户所有管辖单位
     *
     * @param params 其他查询条件
     * @param mngIds 管辖单位的id
     * @return
     */
    @Override
    public PageUtils queryMngListIncludeDept(Map<String, Object> params, List<String> mngIds) {
        Org org = (Org) JSONObject.toBean(JSONObject.fromObject(params.get("dataForm")), Org.class);
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Org> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        Map<String, Object> param = new HashMap<>();
        param.put("userId", UserUtil.getUser().getId());
        if (StringUtils.isNotBlank(org.getOrgCode())) {
            param.put("orgCode", "%" + org.getOrgCode() + "%");
        }
        if (StringUtils.isNotBlank(org.getOrgName())) {
            param.put("orgName", "%" + org.getOrgName() + "%");
        }
        if (StringUtils.isNotBlank(org.getOrgRank())) {
            param.put("orgRank", org.getOrgRank());
        }
        List<Org> orgList = orgMapper.queryMngListIncludeDept(param);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /**
     * 根据机构id查询所有下级机构
     *
     * @param org
     * @return
     */
    @Override
    @Cacheable(value = "orgs", key = "'queryOrgsListExcludeDeptByParentId:' + #org.id + ':' + #org.orgRank") //缓存
    public List<OrgHasChildren> queryOrgsListExcludeDeptByParentId(Org org) {
        return orgMapper.queryOrgsListExcludeDeptByParentId(org);
    }

    @Override
    public PageUtils queryPageGradeOneOrg(Map<String, Object> params, UserVO user) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        if (user.getDefaultOrg().getOrgCode().startsWith("1010")) {
            Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
            OrgExample example = new OrgExample();
            OrgExample.Criteria criteria = example.createCriteria();
            criteria.andOrgCodeLike("1010%");
            criteria.andOrgRankEqualTo("1");
            criteria.andOrgGradeEqualTo("1");
            if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
                criteria.andOrgCodeLike("%" + jsonObject.getString("orgCode") + "%");
            }
            if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
                criteria.andOrgNameLike("%" + jsonObject.getString("orgName") + "%");
            }
            example.setOrderByClause("org_code");
            List<Org> orgs = orgMapper.selectByExample(example);
            pageUtils = new PageUtils(p);
        } else {
            Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
            OrgExample example = new OrgExample();
            OrgExample.Criteria criteria1 = example.createCriteria();
            OrgExample.Criteria criteria2 = example.createCriteria();
            OrgExample.Criteria criteria3 = example.createCriteria();
            OrgExample.Criteria criteria4 = example.createCriteria();
            criteria1.andOrgCodeLike("1020%");
            criteria2.andOrgCodeLike("1030%");
            criteria3.andOrgCodeLike("1050%");
            criteria4.andOrgCodeLike("1090%");
            criteria1.andOrgRankEqualTo("1");
            criteria2.andOrgRankEqualTo("1");
            criteria3.andOrgRankEqualTo("1");
            criteria4.andOrgRankEqualTo("1");
            criteria1.andOrgGradeEqualTo("1");
            criteria2.andOrgGradeEqualTo("1");
            criteria3.andOrgGradeEqualTo("1");
            criteria4.andOrgGradeEqualTo("1");
            if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
                criteria1.andOrgCodeLike("%" + jsonObject.getString("orgCode") + "%");
                criteria2.andOrgCodeLike("%" + jsonObject.getString("orgCode") + "%");
                criteria3.andOrgCodeLike("%" + jsonObject.getString("orgCode") + "%");
                criteria4.andOrgCodeLike("%" + jsonObject.getString("orgCode") + "%");
            }
            if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
                criteria1.andOrgNameLike("%" + jsonObject.getString("orgName") + "%");
                criteria2.andOrgNameLike("%" + jsonObject.getString("orgName") + "%");
                criteria3.andOrgNameLike("%" + jsonObject.getString("orgName") + "%");
                criteria4.andOrgNameLike("%" + jsonObject.getString("orgName") + "%");
            }
            example.or(criteria2);
            example.or(criteria3);
            example.or(criteria4);
            example.setOrderByClause("org_code");
            List<Org> orgs = orgMapper.selectByExample(example);
            pageUtils = new PageUtils(p);
        }
        return pageUtils;
    }

    /**
     * 根据机构id查询机构树（不包含部门）-内存中处理机构
     *
     * @param param 机构id
     * @return
     */
    @Override
    public List<OrgHasChildren> selectAllOrgsByMainId(Map<String, Object> param) {
        if (StringUtils.isNotBlank(param.get("creditCode"))) {
            OrgExample example = new OrgExample();
            OrgExample.Criteria criteria = example.createCriteria();
            criteria.andOrgCodeEqualTo(param.get("creditCode").toString());
            List<Org> orgs = orgMapper.selectByExample(example);
            param.put("mainId", (StringUtils.isNotBlank(orgs) && orgs.size() > 0) ? orgs.get(0).getId() : null);
        }
        List<OrgHasChildren> resultList = new ArrayList<>();
        List<OrgHasChildren> orgs = orgMapper.selectAllOrgsByMainId(param);
        OrgHasChildren rootOrg = new OrgHasChildren();
        for (OrgHasChildren org : orgs) {
            if (param.get("mainId").equals(org.getId())) {
                rootOrg = org;
            }
        }
        OrgHasChildren resultOrg = buildChildTree(rootOrg, orgs);
        resultList.add(resultOrg);
        return resultList;
    }

    private OrgHasChildren buildChildTree(OrgHasChildren currNode, List<OrgHasChildren> orgs) {
        List<OrgHasChildren> childTree = new ArrayList<>();
        for (OrgHasChildren treeNode : orgs) {
            if (treeNode.getParentId().equals(currNode.getId())) {
                childTree.add(buildChildTree(treeNode, orgs));
            }
        }
        currNode.setChildren(childTree);
        return currNode;
    }

    /**
     * 获取所有机构list
     * @return
     */
    @Override
    @Cacheable(value = "orgs", key = "'getAllOrgCompany'") //缓存
    public List<Org> getAllOrgCompany() {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgRankEqualTo(Constant.OrgRank.ORGRANK_COMPANY.getValue());
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        return orgMapper.selectByExample(example);
    }

    /**
     * 向上查询直至顶级
     *
     * @param orgIds
     * @return
     */
    @Override
    public List<TreeUtils> getOrgListByOrgIdUpHasSelf(String[] orgIds) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("orgIds", Arrays.asList(orgIds));
        List<Org> list = orgMapper.getOrgListByOrgIdUpHasSelf(param);
        return TreeUtils.getTreeList(list, "id", "parentId", "orgName", null, null);
    }

    /**
     * 向上查询直至顶级，不包含自己
     *
     * @param orgIds
     * @return
     */
    @Override
    public List<TreeUtils> getOrgListByOrgIdUpHasNoSelf(String[] orgIds) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("orgIds", Arrays.asList(orgIds));
        List<Org> list = orgMapper.getOrgListByOrgIdUpHasNoSelf(param);
        return TreeUtils.getTreeList(list, "id", "parentId", "orgName", null, null);
    }
    
    /**
     * 所有机构分页查询
     *
     * @param params 查询条件{page,limit,dataForm:{orgCode,orgName}}
     * @return 分页数据
     */
    @Override
    public PageUtils queryAllListIncludeDept(Map<String, Object> params){
        Org org = (Org) JSONObject.toBean(JSONObject.fromObject(params.get("dataForm")), Org.class);
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Org> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(org.getOrgCode())) {
            criteria.andOrgCodeLike("%" + org.getOrgCode() + "%");
        }
        if (StringUtils.isNotBlank(org.getOrgName())) {
            criteria.andOrgNameLike("%" + org.getOrgName() + "%");
        }
        if (StringUtils.isNotBlank(org.getOrgRank())) {
            criteria.andOrgRankEqualTo(org.getOrgRank());
        }
        if (StringUtils.isNotBlank(org.getOrgType())) {
            criteria.andOrgTypeEqualTo(org.getOrgType());
        }
        example.setOrderByClause(" id ");
        List<Org> orgList = orgMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    public List<Org> getOrgListByCondition(Map<String, Object> params) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(params.get("orgRank"))){
            criteria.andOrgRankEqualTo(params.get("orgRank").toString());
        }
        if(StringUtils.isNotBlank(params.get("orgType"))){
            criteria.andOrgTypeEqualTo(params.get("orgType").toString());
        }
        criteria.andOrgStatusNotEqualTo(Constant.COMMON_STATUS_DELETED);
        return orgMapper.selectByExample(example);
    }

    /**
     * 根据机构编码更新
     *
     * @param org  机构
     * @param user 用户
     */
    @Override
    public void updateOrgByCode(Org org, UserVO user) {
        OrgExample example = new OrgExample();
        OrgExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(org.getOrgCode());
        orgMapper.updateByExample(org, example);
    }

    /**
     * 新增机构，仅新增
     *
     * @param org  机构
     * @param user 用户
     */
    @Override
    public void addOrgOnly(Org org, UserVO user) {
        Date nowDate = new Date();
        org.setCreater(user.getId());
        if (org.getCreateTime() == null) {
            org.setCreateTime(nowDate);
        }
        org.setModUser(user.getId());
        org.setModTime(nowDate);
        if (org.getType() == null) {
            org.setType("1"); //本系统维护
        }
        orgMapper.insert(org);
    }

    /**
     * 修改机构，仅修改
     *
     * @param org  机构
     * @param user 用户
     */
    @Override
    public void updateOrgOnly(Org org, UserVO user) {
        org.setModUser(user.getId());
        org.setModTime(new Date());
        orgMapper.updateByPrimaryKeySelective(org);
    }
}
